package com.heima.app.gateway.filter;

import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/*
@Component
@Slf4j
@Order(0)

public class AuthorizeFilter implements GlobalFilter {
    private static List<String> urlList=new ArrayList<>();
    //初始化白名单 url路径
    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs");//小刀文档需要放行的路径
    }
    */
/*

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //检查用户的请求路径是否属于白名单路径
        String path = request.getURI().getPath();//login/in
        //属于则直接放行
        for (String url : urlList) {
           if (path.contains(url)){
               return chain.filter(exchange);
           }
        }
        //获取请求头中的token 如果token不存在 直接中止请求，返回401
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();//终止
            return writeMessage(exchange,"token认证失败");

        }
        //解析token
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i<1){
                //如果token有效 去除token中的用户id 重新在设置在请求头中 并执行请求
                Object id = claimsBody.get("id");
                log.info("用户网关认证成功 当前用户登录id：{}",id);
                //修改request
                request.mutate().header("userId",String.valueOf(id));
                //修改exchange
                exchange.mutate().request(request);
                return chain.filter(exchange);//放行
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

//        response.setStatusCode(HttpStatus.UNAUTHORIZED);
//        return response.setComplete();//终止
        return writeMessage(exchange,"token认证失败");
    }

    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
*/

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {
    private static List<String> urlList = new ArrayList<>();
    // 初始化白名单 url路径
    static {
//        urlList.add("/login/in");
        urlList.add("/v2/api-docs");
        urlList.add("/login_auth/");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 获取请求对象 响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //**** 2. 判断当前请求路径是否放行
        String reqUrl = request.getURI().getPath();
        for (String url : urlList){
            if (reqUrl.contains(url)) {
                return chain.filter(exchange);
            }
        }
        // 3. 获取请求头中的token值
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 4. 检查token是否有效
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            // 校验有效
            if(AppJwtUtil.verifyToken(claims)<1){
                // 5. 获取token中存储的用户ID
                Integer id = claims.get("id", Integer.class);
                // 6. 获取到的id值，重写到请求头中，传递到要调用的微服务中
                request.mutate().header("userId", String.valueOf(id)).build();
                exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
}
